import React, { useEffect, useState, useRef } from "react";
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { request } from 'dw-mx-request';

interface File {
    uid: string;
    name: string;
    status: string;
    url: string;
}

interface MaterialUploadProps {
    actionUrl: string;
    fileList: Array<File>;
}

export default function MaterialUpload(props: MaterialUploadProps) {

    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [fileList, setFileList] = useState(props.fileList);

    const handleCancel = () => {
        setPreviewVisible(false);
    }

    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        setPreviewImage(file.url || file.preview);
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    };

    const handleChange = async ({ fileList }) => {
        setFileList(fileList);
    }

    return (
        <div>
            <Upload
                action={props.actionUrl}
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
                multiple={true}
            >
                <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>点击上传</div>
                </div>
            </Upload>
            <Modal
                visible={previewVisible}
                title={previewTitle}
                footer={null}
                onCancel={handleCancel}
            >
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </div>
    )
}

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

